package example.hello_security.user.service;

import example.hello_security.user.domain.Operator;
import example.hello_security.user.repo.UserRepository;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService {

  @Autowired
  UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Operator operator = userRepository.findByName(username);
    if (Objects.isNull(operator))
      throw new UsernameNotFoundException("user not found");
    return org.springframework.security.core.userdetails.User.withUsername(operator.getName())
        .password(operator.getPassword())
        .authorities(operator.getRole())
        .build();
  }
}
